package com.qzsoft.zhjd.laboratory.modules.tensionRecording.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qzsoft.jeemis.common.utils.Result;
import com.qzsoft.jeemis.platform.security.user.SecurityUser;
import com.qzsoft.zhjd.common.components.BaseServiceComponent;
import com.qzsoft.zhjd.common.utils.DateUtils;
import com.qzsoft.zhjd.common.utils.ResultUtils;
import com.qzsoft.zhjd.laboratory.modules.tensionProcess.entity.TensionProcess;
import com.qzsoft.zhjd.laboratory.modules.tensionProcess.service.TensionProcessService;
import com.qzsoft.zhjd.laboratory.modules.tensionRecording.entity.TensionRecording;
import com.qzsoft.zhjd.laboratory.modules.tensionRecording.mapper.TensionRecordingMapper;
import com.qzsoft.zhjd.laboratory.modules.tensionRecording.service.TensionRecordingService;
import com.qzsoft.zhjd.laboratory.modules.tensionResult.entity.TensionResult;
import com.qzsoft.zhjd.laboratory.modules.tensionResult.service.TensionResultService;
import lombok.AllArgsConstructor;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 张拉记录(TensionRecording)表服务实现类
 *
 * @author makejava
 * @since 2023-07-12 13:36:33
 */
@Service("tensionRecordingService")
@AllArgsConstructor
public class TensionRecordingServiceImpl extends ServiceImpl<TensionRecordingMapper, TensionRecording> implements TensionRecordingService {

    @Autowired
    private BaseServiceComponent baseServiceComponent;
    @Autowired
    private TensionResultService resultService;
    @Autowired
    private TensionProcessService processService;

    @Override
    public IPage<TensionRecording> page(Map<String, Object> params) {
        IPage<TensionRecording> page = baseServiceComponent.getPage(params, TensionRecording.class);
        return baseMapper.query(page, params);
    }

    /**
     * 查询
     *
     * @param id
     * @return
     */
    @Override
    public TensionRecording getInfoById(String id) {
        return getById(id);
    }

    /**
     * 新增
     *
     * @param tensionRecording
     * @return
     */
    @Override
    public void insertTensionRecording(TensionRecording tensionRecording) {
        tensionRecording.setId(IdWorker.get32UUID());
        //创建者
        tensionRecording.setCreateBy(SecurityUser.getUserId());
        //创建时间
        tensionRecording.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        save(tensionRecording);
        //进行linkCode码推送
        try{
            tensioningDataSend(tensionRecording.getLinkCode());
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 修改
     *
     * @param tensionRecording
     */
    @Override
    public void updateTensionRecordingById(TensionRecording tensionRecording) {
        //修改者
        tensionRecording.setUpdateBy(SecurityUser.getUserId());
        //修改时间
        tensionRecording.setUpdateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
        updateById(tensionRecording);
    }

    /**
     * 删除 批量/单个
     *
     * @param ids
     */
    @Override
    public void deleteByIds(List<String> ids) {
        removeByIds(ids);
    }
    /**
     * 张拉整合信息接收接口
     * @param tensionJson
     * @return
     */
    @Override
    @Transactional
    public Result tensioningDataReception(JSONObject tensionJson) {
        //转换recording数据
        TensionRecording recording= JSONUtil.toBean(tensionJson,TensionRecording.class);
        QueryWrapper<TensionRecording> query = new QueryWrapper<>();
        query.eq("code",recording.getCode());
        query.eq("beam_type",recording.getBeamType());
        query.eq("beam_no",recording.getBeamNo());
        query.eq("stake",recording.getStake());
        query.eq("tension_time",recording.getTensionTime());
        query.eq("deflection_upwards",recording.getDeflectionUpwards());
        query.eq("concrete_design",recording.getConcreteDesign());
        query.eq("concrete_strength",recording.getConcreteStrength());
        query.eq("loading_speed",recording.getLoadingSpeed());
        query.eq("tensile_stress",recording.getTensileStress());
        query.eq("device_number",recording.getDeviceNumber());
        List<TensionRecording> tsResult = this.list(query);
        //判定数据是否已存在
        if(tsResult.size()==0){
            //转换result数据
            JSONArray resultListJson = tensionJson.getJSONArray("resultList");
            List<TensionResult> resultList =  JSONUtil.toList(resultListJson, TensionResult.class);
            //转换process数据
            JSONArray processListJson = tensionJson.getJSONArray("processList");
            List<TensionProcess> processList =  JSONUtil.toList(processListJson, TensionProcess.class);
            //自动生成关联ID
            String linkCode = UUID.randomUUID().toString().replace("-","");
            //填充linkCode
            recording.setLinkCode(linkCode);
            if(resultList!=null&&processList!=null){
                resultList.stream().forEach(result -> {
                    result.setId(IdWorker.get32UUID());
                    //创建者
                    result.setCreateBy(SecurityUser.getUserId());
                    //创建时间
                    result.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
                    result.setLinkCode(linkCode);
                    //------------判断该数据是否存在于数据库，如若已存在，则去除已存在数据的关联关系(即去除旧数据linkCode值)
                    QueryWrapper<TensionResult> resultQuery = new QueryWrapper<>();
                    resultQuery.eq("code",result.getCode());
                    resultQuery.eq("hole_number",result.getHoleNumber());
                    resultQuery.eq("device_code",result.getDeviceCode());
                    resultQuery.eq("tensioning_time",result.getTensioningTime());
                    resultQuery.eq("tensioning_section",result.getTensioningSection());
                    resultQuery.eq("measurement_point",result.getMeasurementPoint());
                    List<TensionResult> list =resultService.list(resultQuery);
                    //去除旧数据LinkCode值
                    if(list.size()>0){
                        list.stream().forEach(tensionResult -> {
                            tensionResult.setLinkCode(null);
                            resultService.updateById(tensionResult);
                        });
                    }
                    });
                processList.stream().forEach(process -> {
                    process.setId(IdWorker.get32UUID());
                    //创建者
                    process.setCreateBy(SecurityUser.getUserId());
                    //创建时间
                    process.setCreateTime(DateUtils.getDate("yyyy-MM-dd HH:mm:ss"));
                    process.setLinkCode(linkCode);
                });
                //数据插入处理
                this.insertTensionRecording(recording);
                resultService.saveBatch(resultList);
                processService.saveBatch(processList);
            }else {
                return ResultUtils.error("resultList及processList不可为空值!");
            }
            //进行linkCode码推送
//            try{
//                tensioningDataSend(recording.getLinkCode());
//            } catch (Exception e){
//                e.printStackTrace();
//            }
        }else{
            return ResultUtils.error("该数据已存在!");
        }

        return ResultUtils.ok();
    }
    private void tensioningDataSend(String linkCode) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet("http://111.14.222.59:9163/prod-api/zhgd/nLaboratoryTensionRequires/isQualified?linkCode="+linkCode);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            // 对得到后的实例可以进行处理，例如读取回复体，读取html
            HttpEntity entity = response.getEntity();
            System.out.println(new Date());
            System.out.println("=======================");
            String html = EntityUtils.toString(entity);
            System.out.println(html);
        } else {
            throw new ClientProtocolException("Unexpected response status: " + status);
        }
        // 6. 释放连接
        response.close();
        httpClient.close();
    }
}

